﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Oplaco.Core.BusinessLogicLayer;
using System.Xml.Linq;
using System.Web;
using Oplaco.Core.Configuration;

namespace Oplaco.Web.UI
{    
    /// <summary>
    /// 
    /// </summary>
    /// <example>
    /// AdType a = AdType.ForSale;
    /// Console.WriteLine(String.Format(new AdTypeFormatProvider(), "AdType: {0}", a));
    /// </example>
    public class AdTypeFormatter : ICustomFormatter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="format"></param>
        /// <param name="o"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public string Format(string format, object o, IFormatProvider formatProvider)
        {
            RegionInfo UserRegion = new RegionInfo(CultureInfo.CurrentCulture.Name);

            if (!o.GetType().Equals(typeof(AdType)))
            {
                return o.ToString();
            }
            else
            {
                SiteSettings settings = SiteSettings.GetSharedSettings();
                if (settings.SitePreferUserCulture)
                {
                    AdType adtype = (AdType)o;
                    int adTypeIntegerValue = (int)o;
                    XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath(settings.AdTypeCultureInfoFile));
                    var result = from a in doc.Descendants("AdTypes").Elements("AdType") where a.Attribute("BaseType").Value.Equals(adTypeIntegerValue.ToString()) && a.Attribute("Region").Value.Equals(UserRegion.Name) select a.Attribute("Name");
                    if (result != null && result.Count() > 0)
                    {
                        return result.First().Value;
                    }

                    //fall back to default
                    return o.ToString();
                }
                else {
                    return o.ToString();
                }
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class AdTypeFormatProvider : IFormatProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="formatType"></param>
        /// <returns></returns>
        public object GetFormat(Type formatType)
        {
            return (formatType == typeof(ICustomFormatter)) ? new AdTypeFormatter() : null;
        }
    }
}
